// initial state
import {LocalStorageService} from "../../services/LocalStorageService";

const state = () => ({
    userToken: null,
    userInfo: null
})

// getters
const getters = {
    userInfo: (state, getters) => {
        return state.userInfo || LocalStorageService.getItem('user')
    },
    userToken: (state, getters) => {
        return state.userToken || LocalStorageService.getItem('token')
    }
}

// actions
const actions = {
    async saveUser({commit, state}, userInfo) {
        commit('setUserToken', userInfo.token)
        commit('setUserInfo', userInfo.user)

        // 保存到 localStorage
        LocalStorageService.setItem('token', userInfo.token);
        LocalStorageService.setItem('user', userInfo.user);
    },
}

// mutations
const mutations = {
    setUserToken(state, userToken) {
        state.userToken = userToken
    },
    setUserInfo(state, userInfo) {
        state.userInfo = userInfo
    }
}

export default {
    // namespaced: true,
    state,
    getters,
    actions,
    mutations,
}
